package com.study.business.user.service;

import cn.hutool.http.HttpStatus;
import com.study.business.user.domain.User;
import com.study.business.user.mapper.UserMapper;
import com.study.business.util.Md5Util;
import com.study.business.util.ResponseFailed;
import com.study.business.util.ResponseSuccess;
import com.study.business.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangyi
 */
@Transactional(rollbackFor = Exception.class)
@Service
@Slf4j
public class UserService implements UserDetailsService {


    private static final String URL = "http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=json&version=1.1&q=";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private UserMapper userDao;


    public String translate(String string) {
        log.info("in service translate");
        ResponseEntity<String> res = null;
        try {
            res = restTemplate.getForEntity(URL + string, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        if (res != null && res.getStatusCode() != null && res.getStatusCode().value() == HttpStatus.HTTP_OK) {
            return res.getBody();
        }
        return null;
    }

    public List<User> getAll() {
        try {
            return userDao.getAll();
        } catch (DataAccessException e) {
            log.error("查询出现异常 " + e);
            throw new IllegalArgumentException(e);
        }
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.DEFAULT)
    public boolean addUser(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        user.setCreateTime(new Date());
        user.setPassword(Md5Util.getEncryptedPwd(user.getPassword()));
        return userDao.addUser(user);
    }


    public ResponseUtil deleteUser(String id) {
        log.info("查询map" + userDao.getUser(id).toString());
        boolean result = userDao.deleteUser(id);
        if (result) {
            return new ResponseSuccess("deleteSuccess");
        }
        return new ResponseFailed();
    }

    public ResponseUtil updateUser(int id, User user) {
        user.setId(id);
        boolean result = userDao.updateUser(user);
        if (result) {
            return new ResponseSuccess("updateSuccess");
        }
        return new ResponseFailed();
    }

    public ResponseUtil checkUser(User user) {

        User userTmp = userDao.findUser(user.getNickName());
        SecurityContext securityContext;
        if ((securityContext = SecurityContextHolder.getContext()) != null) {
            boolean equals = user.getNickName().equals(securityContext.getAuthentication().getName());
            if (equals) {
                log.info("缓存中已经存在用户!");
                return new ResponseSuccess(userTmp);
            }

        }

        if (userTmp != null) {
            String password = encoder.encode(user.getPassword());
            if (userTmp.getPassword().equalsIgnoreCase(password)) {

                return new ResponseSuccess(userTmp);
            }
//                boolean result = Md5Util.validPassword(user.getPassword(), userTmp.getPassword());
//                if (result) {
//                }
        }
        return new ResponseFailed();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("Hello world!");
        User userTmp = userDao.findUser(username);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("admin"));
        userTmp.setAuthorities(list);
        return userTmp;
    }
}
